package com.srwl.mytx.widget.chatRow;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.srwl.mytx.R;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.AliOssService;

import java.io.File;

import static com.srwl.mytx.fragment.BaseChatFragment.isVoiceAutoPlay;


public class ChatRowVoice extends ChatRowFile {
    private static String TAG = "ChatRowVoice";
    private float scale;

    private ImageView voiceImageView;
    private TextView voiceLengthView;
    private ImageView readStatusView;
    private AnimationDrawable voiceAnimation = null;
    //用来标识此语音消息是否是一条新消息(未读消息)
    private boolean isNewMessage;


    public ChatRowVoice(View itemView) {
        super(itemView);
    }

    @Override
    protected void onInflateView() {

    }

    @Override
    protected void onFindViewById(View itemView) {
        voiceImageView = itemView.findViewById(R.id.iv_voice);
        voiceLengthView = itemView.findViewById(R.id.tv_length);
        readStatusView = itemView.findViewById(R.id.iv_unread_voice);
    }


    @Override
    protected void onSetUpView() {
        Integer voiceLength = message.getPlayTime();
        if (voiceLength != null && voiceLength > 0) {

            voiceLengthView.setText(voiceLength + "\"");
            voiceLengthView.setVisibility(View.VISIBLE);
            //设置语音信息气泡的长度
            scale = context.getResources().getDisplayMetrics().density;
            voiceLength = voiceLength > 60 ? 60 : voiceLength;
            int height = (int) ((double) (this.scale * 30.0F) + 0.5D);
            int width = (int) ((double) this.scale * (54.0D + 1.694915254237288D * (double) voiceLength) + 0.5D);
            // LayoutParams params = new LayoutParams(width, height);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) bubbleLayout.getLayoutParams();
            params.width = width;
            bubbleLayout.setLayoutParams(params);
        } else {
            voiceLengthView.setVisibility(View.INVISIBLE);
        }
        //当在播放语音的时候== 在执行播放动画的时候 滑动屏幕，会导致动画消失或无故出现，所以根据播放状态，设置静态背景图片或者播放动画


        if (ChatRowAudioPlayer.getInstance(context).isPlaying() && ChatRowAudioPlayer.getInstance(context).isCurrentMsgPlaying(message)) {
            ChatRowAudioPlayer.getInstance(context).setInteractionListener(generatePlayerListener());
            showAnimation();
        } else {
            if (isSendMessage) {
                voiceImageView.setImageResource(R.drawable.ease_chatto_voice_playing);
            } else {
                voiceImageView.setImageResource(R.drawable.ease_chatfrom_voice_playing);
            }
        }
        if (!isSendMessage) {
            if (message.getReadState() == Constant.MESSAGE_READ_STATE_READ) {
                readStatusView.setVisibility(View.INVISIBLE);
                isNewMessage = false;
            } else {
                isNewMessage = true;
                readStatusView.setVisibility(View.VISIBLE);
            }

            String audioKey = message.getContent();
            Integer downloadState = message.getDownloadState();
            //如果下载状态为空，说明是第一次加载，设置下载状态为初始化
            if (downloadState == null) {
                downloadState = Constant.MESSAGE_DOWNLOAD_STATE_INIT;
            }
            switch (downloadState) {
                case Constant.MESSAGE_DOWNLOAD_STATE_INIT:
                    Log.d(TAG, "初次加载语音文件:" + message.getId());
                    progressBar.setVisibility(View.VISIBLE);
                    //又文件读写权限，才去下载文件，否则下载了保存也会报权限异常
                    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_LOADING);
                        downLoadAudioFile(audioKey);
                    }
                    break;
                case Constant.MESSAGE_DOWNLOAD_STATE_LOADING:
                    progressBar.setVisibility(View.VISIBLE);
                    break;
                case Constant.MESSAGE_DOWNLOAD_STATE_SUCCESS:
                    progressBar.setVisibility(View.INVISIBLE);
                    //再次检查,不知道怎么会出现，加载过一次，下载状态都更新为 success了，本地却找不到 下载音频文件，只好在这儿再做一次判断
                    File file = new File(Helper.getInstance().getFilePath(), audioKey);
                    //检查文件是否存在，如果存在，就直接 返回true
                    if (!file.exists()) {
                        Log.d(TAG, "语音文件不存在，再次加载语音文件:" + message.getId());
                        downLoadAudioFile(audioKey);
                        break;
                    }
                    //如果开启了语音自动播放，并且当前没有语音信息在播放，并且该语音消息是一条新消息
                    if (isVoiceAutoPlay && !ChatRowAudioPlayer.getInstance(context).isPlaying() && isNewMessage) {
                        Log.d(TAG, "onSetUpView: 开始自动播放语音消息" + message.getId());
                        playAudioMessage();
                    }
                    break;
                case Constant.MESSAGE_DOWNLOAD_STATE_FAIL:
                    progressBar.setVisibility(View.INVISIBLE);
                    Integer reDownLoadCount = message.getReDownLoadCount();
                    if (reDownLoadCount == null) {
                        reDownLoadCount = 0;
                    }
                    if (reDownLoadCount < 2) {
                        message.setReDownLoadCount(reDownLoadCount + 1);
                        Log.d(TAG, "加载图片失败后重新加载:" + message.getId() + "当前重试次数：" + reDownLoadCount + 1);
                        progressBar.setVisibility(View.VISIBLE);
                        message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_LOADING);
                        downLoadAudioFile(audioKey);
                    }
            }

        }

    }

    private void downLoadAudioFile(String audioKey) {
        AliOssService.getInstance().downloadAudio(audioKey, new AliOssService.OssListener() {
            @Override
            public void onProgressChange(int progress) {
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setProgress(progress);
                    }
                });
            }

            @Override
            public void onSuccess(String objectKey) {
                message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_SUCCESS);
                messageDao.update(message);
                ((Activity) context).runOnUiThread(() -> adapter.notifyItemChanged(getAdapterPosition()));
            }

            @Override
            public void onFailure(String errorCode, String content) {
                message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_FAIL);
                messageDao.update(message);
                ((Activity) context).runOnUiThread(() -> adapter.notifyItemChanged(getAdapterPosition()));
            }
        });
    }

    @Override
    protected void onBubbleClick() {
        //如果是接收到的消息，并且消息的状态不是下载成功，就返回，文件下载成功前，禁止播放
        if (!isSendMessage && message.getDownloadState() != Constant.MESSAGE_DOWNLOAD_STATE_SUCCESS) {
            Log.i(TAG, "onBubbleClick: 语音消息没有下载成功，，，");
            return;
        }
        playAudioMessage();

    }


    private void playAudioMessage() {
        ChatRowAudioPlayer.getInstance(context).play(message, generatePlayerListener());
    }

    private ChatRowAudioPlayer.AudioPlayerInteractionListener generatePlayerListener() {
        return new ChatRowAudioPlayer.AudioPlayerInteractionListener() {
            @Override
            public void onStartPlay() {
                Log.d(TAG, "onStartPlay: 开始播放");
                showAnimation();

                //如果当前语音消息是接收到的新消息，开始播放语音后，隐藏掉readStatusView，并设置该消息的状态为已读，
                if (isNewMessage && !isSendMessage) {
                    // 隐藏语音信息未播放消息标志

                    readStatusView.setVisibility(View.INVISIBLE);
                    //更新该信息本地状态为已读
                    //  audioBody.setHasRead(YWMessageType.ReadState.read);
                    message.setReadState(Constant.MESSAGE_READ_STATE_READ);
                    //更新该消息在服务端的状态为已读
                    if (chatRowCallBack != null) {
                        chatRowCallBack.onMessageRead(message);
                    }

                }

            }

            @Override
            public void onBreakPlay() {
                Log.d(TAG, "onBreakPlay: 播放中断");
                hideAnimation();
            }

            @Override
            public void onCompletePlay() {
                Log.d(TAG, "onCompletePlay: 播放完成");
                hideAnimation();
                //如果当前播放完成的语音消息是一条接收到的新消息，没播放放过的就算新消息，那就通知出去，在messageAdapter中，做处理，看是否需要自动播放
                if (chatRowCallBack != null && !isSendMessage) {
                    chatRowCallBack.onAudioPlayCompletion(position);
                }
            }

            @Override
            public void onError(int errorCode, String content) {
                Log.d(TAG, "onError: 播放错误");
                hideAnimation();
                if (errorCode == -1) {
                    if (isSendMessage) {
                        downLoadAudioFile(message.getId());
                    } else { //其实不管是发送消息还是接收的消息，消息的id 就是 文件类型消息的文件 key
                        downLoadAudioFile(message.getContent());
                    }
                }
            }
        };

    }

    private void showAnimation() {

        if (voiceAnimation != null && voiceAnimation.isRunning()) {
            return;
        }

        if (isSendMessage) {
            voiceImageView.setImageResource(R.drawable.voice_to_icon);
        } else {
            voiceImageView.setImageResource(R.drawable.voice_from_icon);
        }
        voiceAnimation = (AnimationDrawable) voiceImageView.getDrawable();
        voiceAnimation.start();
        Log.d(TAG, "showAnimation: 开始播放动画");
    }

    private void hideAnimation() {
        if (voiceAnimation != null) {
            voiceAnimation.stop();
            Log.d(TAG, "hideAnimation: 停止播放动画");
            voiceAnimation = null;
        } else {
            Log.e(TAG, "hideAnimation:voiceAnimation为空 ，无法停止动画");
        }
        if (isSendMessage) {
            voiceImageView.setImageResource(R.drawable.ease_chatto_voice_playing);
        } else {
            voiceImageView.setImageResource(R.drawable.ease_chatfrom_voice_playing);
        }
    }


    public void autoPlay() {
        onBubbleClick();
    }


}
